<template>
  <div>
    <n-card :bordered="false" title="网络参数" class="mt-4 proCard">
      <n-grid cols="1 s:1 m:3 l:3 xl:3 2xl:3" responsive="screen">
        <n-grid-item offset="0 s:0 m:1 l:1 xl:1 2xl:1">
          <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
            <template #ip>
              <n-input-group>
                <n-input v-model:value="ip.ip0" @update:value="handleIpChange" />
                <n-input-group-label>.</n-input-group-label>
                <n-input v-model:value="ip.ip1" @update:value="handleIpChange" />
                <n-input-group-label>.</n-input-group-label>
                <n-input v-model:value="ip.ip2" @update:value="handleIpChange" />
                <n-input-group-label>.</n-input-group-label>
                <n-input v-model:value="ip.ip3" :disabled="true" />
              </n-input-group>
            </template>
          </BasicForm>
        </n-grid-item>
      </n-grid>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { onMounted, reactive } from 'vue';
  import { getNetWorkInfo, NetWork, updateNetWorkInfo } from '@/api/basicconfig/basicconfig';
  import { useMessage } from 'naive-ui';
  import type { FormItemRule } from 'naive-ui';
  import { isIp } from '@/utils/is';

  const message = useMessage();

  const ip = reactive({
    ip0: '',
    ip1: '',
    ip2: '',
    ip3: '',
  });

  const schemas: FormSchema[] = [
    {
      field: 'name',
      component: 'NInput',
      label: '节点名称',
      rules: [{ required: true, message: '请输入节点名称', trigger: ['blur'] }],
    },
    {
      field: 'id',
      component: 'NInputNumber',
      label: '节点ID',
      componentProps: {
        min: 0,
        max: 252,
        onUpdateValue: (value: number | null) => {
          //console.log(value);
          ip.ip3 = value !== null && value !== undefined ? `${value + 1}` : '';
        },
      },
      rules: [
        //{ required: true, message: '请输入节点ID', trigger: ['blur'] },
        { required: true, message: '请输入节点ID', type: 'number', trugger: ['blur'] },
      ],
    },
    {
      field: 'ip',
      component: 'NInputGroup',
      slot: 'ip',
      label: 'IP',
      rules: [
        { required: true, message: '请输入IP地址', trigger: ['blur'] },
        {
          message: 'IP格式不正确',
          validator(rule: FormItemRule, value: string) {
            const fullIp = `${ip.ip0}.${ip.ip1}.${ip.ip2}.${ip.ip3}`;
            return isIp(fullIp);
          },
        },
      ],
    },
    {
      field: 'nwMask',
      component: 'NInput',
      label: '子网掩码',
    },
    {
      field: 'gateway',
      component: 'NInput',
      label: '默认网关',
    },
    {
      field: 'dnsServer',
      component: 'NInput',
      label: '子网域名服务器',
    },
  ];

  const [register, { validate, setFieldsValue }] = useForm({
    labelWidth: 120,
    gridProps: { cols: 1 },
    collapsedRows: 3,
    layout: 'horizontal',
    submitOnReset: false,
    isFull: true,
    submitButtonText: '提交',
    showSubmitButton: true,
    showResetButton: true,
    schemas,
  });

  function handleIpChange() {
    console.log('触发ip验证');
    validate(['ip']);
  }

  async function handleSubmit(value: Recordable) {
    // console.log(value);
    // let res = await validate(['ip']);
    // console.log(res);
    // console.log({ ...value, ...{ ip: `${ip.ip0}.${ip.ip1}.${ip.ip2}.${ip.ip3}` } });
    updateNetWorkInfo({
      ...value,
      ...{ ip: `${ip.ip0}.${ip.ip1}.${ip.ip2}.${ip.ip3}` },
    } as NetWork)
      .then((result) => {
        //console.log('result', result);
        if (result === 'OK') {
          message.success('网络参数设置成功！');
        } else {
          message.error('网络参数设置失败！');
        }
      })
      .catch((err) => {
        //console.log(err);
        message.error('网络参数设置失败！');
      });
  }

  function handleReset(values: Recordable) {
    // console.log(values);
    ip.ip0 = '';
    ip.ip1 = '';
    ip.ip2 = '';
    ip.ip3 = '';
  }

  onMounted(async () => {
    try {
      const networkInfo = await getNetWorkInfo();
      //console.log('networkInfo', networkInfo);
      setFieldsValue(networkInfo);
      const ips = networkInfo.ip.split('.');
      //console.log(ips);
      ip.ip0 = ips[0];
      ip.ip1 = ips[1];
      ip.ip2 = ips[2];
      ip.ip3 = ips[3];
    } catch (error) {
      //console.log(error);
      message.error('获取网络信息失败！');
    }
  });
</script>
